const Base = require('./base')
const MsgCrypt = require('./msg_crypto')
const querystring = require('querystring')
module.exports = class extends Base {
  /**
     * getComponentVerifyTicket
     * @param ticket
     */
  async getComponentVerifyTicket (ticket) {
    const cryptor = new MsgCrypt(this.conf.msg_token, this.conf.msg_encode, this.conf.appid)
    const xml = cryptor.decryptMsg(ticket.msg_signature, ticket.timestamp, ticket.nonce, ticket.Encrypt)
    const d = await this.xmlformat(xml)
    await think.cache(`component_verify_ticket`, d.ComponentVerifyTicket)
    return d
  }

  /**
     * 获取 component_access_token
     * @param component_verify_ticket
     */
  async getComponentAccessToken (componentVerifyTicket = null) {
    let componentAccessToken = await think.cache('component_access_token')
    if (!componentAccessToken) {
      componentVerifyTicket = componentVerifyTicket || await think.cache('component_verify_ticket')
      const url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
      const data = {
        component_appid: this.conf.appid,
        component_appsecret: this.conf.appsecret,
        component_verify_ticket: componentVerifyTicket
      }
      const d = await yy.http.post(url, data)
      componentAccessToken = d.component_access_token
      await think.cache(`component_access_token`, d.component_access_token, { type: 'file', file: { timeout: 5900 * 1000 } })
    }
    yy.log.info('=== getComponentAccessToken ===', componentAccessToken)
    return componentAccessToken
  }

  async refreshComponentToken (ticket) {
    ticket = ticket || await think.cache('component_verify_ticket')
    yy.log.debug('refreshComponentToken', ticket)
    const d = await yy.http.post('https://api.weixin.qq.com/cgi-bin/component/api_component_token', {
      component_appid: this.conf.appid,
      component_appsecret: this.conf.appsecret,
      component_verify_ticket: ticket
    })
    await think.cache(`component_access_token`, d.component_access_token, { type: 'file', file: { timeout: 5900 * 1000 } })
    return d
  }

  /**
     * 获取 getPreAuthCode
     * @param component_access_token
     */
  async getPreAuthCode (componentAccessToken = null) {
    let preAuthCode = ''// 不能重复使用pre_auth_code
    componentAccessToken = componentAccessToken || await this.getComponentAccessToken()
    const url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' + componentAccessToken
    const data = { component_appid: this.conf.appid }
    const d = await yy.http.post(url, data)
    yy.log.info('=== getPreAuthCode ===', d)
    preAuthCode = d.pre_auth_code
    return preAuthCode
  }

  /**
     * 获取公众号权限信息
     * @param getData
     * @returns {*}
     */
  async getApiQueryAuth (getData) {
    let d = {}
    if (getData.auth_code) {
      const componentAccessToken = await think.cache('component_access_token')
      const url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' + componentAccessToken
      d = await yy.http.post(url, {
        component_appid: this.conf.appid,
        authorization_code: getData.auth_code
      })
      yy.log.info('=== getApiQueryAuth ===', d)
      if (d.authorization_info && d.authorization_info.authorizer_appid) {
        // access_token信息
        await think.cache(`access_token_${d.authorization_info.authorizer_appid}`, d.authorization_info.authorizer_access_token, { type: 'file', file: { timeout: 6500 * 1000 } })
      }
    }
    return d.authorization_info
  }
  /**
     * 获取公众号基本信息
     * @param authorizer_appid 公众号id
     * @returns {{}}
     */
  async getBaseInfo (appid = null) {
    let d = {}
    if (appid) {
      const token = await think.cache('component_access_token')
      d = await yy.http.post(`https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=${token}`, {
        component_appid: this.conf.appid,
        authorizer_appid: appid
      })
      yy.log.debug(d)
      // 保存到数据库
      d.id = await yy.model('wx_authorizer').saveAuthorizer(d)
    }
    return d
  }

  /**
     * 生成二维码链接
     * @param fromUrl 从哪个页面进来
     * @returns {*}
     */
  async getAuthUrl (fromUrl) {
    const preAuthCode = await this.getPreAuthCode()
    const query = {
      component_appid: this.conf.appid,
      pre_auth_code: preAuthCode,
      redirect_uri: `https://mp.vco.fun/wechat/open/signin?from_url=${fromUrl}`
    }
    yy.log.info('=== getAuthUrl ===', query)
    // return `https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=${this.conf.appid}&pre_auth_code=${pre_auth_code}&redirect_uri=${redirect_uri}`
    return `https://mp.weixin.qq.com/cgi-bin/componentloginpage?${querystring.stringify(query)}`// 跳转到公众号扫描授权
  }
}
